package com.zhilianbao.leyaogo.ui.fragment.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.roundview.RoundTextView;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.listener.OnAddToCartClickListener;
import com.zhilianbao.leyaogo.model.response.category.GoodsInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.shoppingcart.ShoppingCartActivity;
import com.zhilianbao.leyaogo.ui.adapter.home.GoodsClassifyListAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.RefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.ShopNumUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * ClassName: GoodsClassifyListFragment <br>
 * Description: 商品分类列表<br>
 * Author: Cyarie <br>
 * Created: 2016/12/29 10:21 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class GoodsClassifyListFragment extends RefreshAndLoadFragment<GoodsInfo> implements OnAddToCartClickListener<GoodsInfo> {

    @BindView(R.id.tv_activity_info)
    TextView mTvActivityInfo;
    private GoodsClassifyListAdapter mGoodsClassifyListAdapter;

    private int customClassifyId;

    private String title;

    @BindView(R.id.iv_add_to_cart)
    ImageView mIvAddToCart;
    @BindView(R.id.iv_cart_num)
    RoundTextView mIvCartNum;
    @BindView(R.id.rl_add_to_cart)
    RelativeLayout mRlAddToCart;
    @BindView(R.id.rl_content)
    MyRelativeLayout mRlContent;

    public static GoodsClassifyListFragment getInstance(Bundle bundle) {
        GoodsClassifyListFragment goodsClassifyListFragment = new GoodsClassifyListFragment();
        goodsClassifyListFragment.setArguments(bundle);
        return goodsClassifyListFragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        //进入商品详情
        Utils.startGoodsDetails(mActivity, mList.get(position).getGoodsId(), mList.get(position).getGoodsSkuId(), false);
    }

    @OnClick({R.id.iv_add_to_cart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add_to_cart:
                Utils.startActivity(mActivity, ShoppingCartActivity.class);
                break;
        }
    }

    @Override
    public QuickRcvAdapter<GoodsInfo> getAdapter() {
        return mGoodsClassifyListAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(mActivity, 2);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_special_activity;
    }

    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        CategoryApi.getHomeGoodsList(mActivity, Utils.getSupplierId(), customClassifyId, curPage, pageSize, new RefreshAndLoadCallback<List<GoodsInfo>>(isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                loadDataList(1, false);
            }

            @Override
            public void onResultSuccess(List<GoodsInfo> list, @Nullable Response response, LoadingViewCallback callback) {
                handleRefreshAndLoadListData(curPage, callback, list);
                if (curPage == 1 && list.size() == 0) {
                    mRlAddToCart.setVisibility(View.GONE);
                } else if (curPage == 1 && list.size() != 0) {
                    mRlAddToCart.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mTvActivityInfo.setVisibility(View.GONE);
        mRcvLoadMore.setPadding(0, Utils.dp2px(8), Utils.dp2px(4), Utils.dp2px(4));
        mRcvLoadMore.setClipToPadding(false);
        ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
    }

    @Override
    protected void initToolbarHere() {
        mGoodsClassifyListAdapter = new GoodsClassifyListAdapter(mActivity, mList, this);
        customClassifyId = (int) getArguments().getLong(IntentConfig.ACTIVITY_ID, 0);
        title = getArguments().getString(IntentConfig.ACTIVITY_TITLE, "");
        initToolbar(title);
    }

    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    @Override
    public void onAddToCartClick(GoodsInfo item, ImageView imageView) {
        if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
            addToCart(item, imageView);
        } else {
            LogicCodeBlock.create().registerLogicCodeCallback(logicState -> {
                if (logicState == LogicCodeBlock.LogicState.AddToCart.value)
                    addToCart(item, imageView);
            });
        }
    }

    /**
     * 加入购物车
     *
     * @param item
     * @param imageView
     */
    private void addToCart(GoodsInfo item, ImageView imageView) {
        ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), item.getGoodsId(), Utils.getSupplierId(), item.getShopId(), item.getGoodsSkuId(), 1, 0, new DialogCallback<GoodsStock>(mActivity/*, getString(R.string.adding)*/) {
            @Override
            public void onSuccess(GoodsStock o, Call call, Response response) {

                ShopAnimationUtils.addToShoppingCart(mActivity, 2, imageView, mIvAddToCart, mRlContent, true, () -> {
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                    ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
                });
            }
        });
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY://从分组进入购物车,点击去逛逛,finish掉该页面
                mActivity.finish();
                break;
        }
    }
}
